package com.example.administrator.chinafood;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.chinafood.Adapter.FoodListView;
import com.example.administrator.chinafood.Adapter.MyListViewAdapter;
import com.example.administrator.chinafood.ToJsonResult.AllResult;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/11/1.
 */

public class FlFood extends Fragment {

    private ListView list;
    private MyListViewAdapter<FoodListView> myAdapter = null;
    private List<FoodListView> mData1 = null;
    private Context context;

    private Spinner sp1,sp2;

    private EditText editText;
    private int lastVisibleItem;
    private int totalItems;
    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fl_food, container, false);
        context = view.getContext();
        list = (ListView) view.findViewById(R.id.list_food);
        //listview 事件，根据选择展示所选数据
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView txt_title = (TextView)view.findViewById(R.id.txt_list_title);
                String str = txt_title.getText().toString().trim();
                Intent intent = new Intent();
                intent.putExtra("foodname",str);
                intent.setClass(context, TheFood.class);
                startActivity(intent);
            }
        });
        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (lastVisibleItem == totalItems && scrollState == SCROLL_STATE_IDLE) {
                    getData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastVisibleItem=firstVisibleItem+visibleItemCount;
                totalItems = totalItemCount;
            }
        });

        init();

        sp1 = (Spinner) view.findViewById(R.id.food_sp1);
        sp2 = (Spinner) view.findViewById(R.id.food_sp2);

        //根据选项加载sp2的不同数据
        sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                                context, R.array.foodType_0,
                                android.R.layout.simple_spinner_dropdown_item);
                        sp2.setAdapter(adapter);
                        break;
                    case 1:
                        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
                                context, R.array.foodType_1,
                                android.R.layout.simple_spinner_dropdown_item);
                        sp2.setAdapter(adapter1);
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //根据sp2的选择，加载不同的对应数据
        sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mData1.clear();
                bit.clear();
                setData(position+2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        editText = (EditText) view.findViewById(R.id.food_ed);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    String select = editText.getText().toString().trim();
                    selectFood(select);
                }
                return false;
            }
        });
        return view;
    }

    private void setData(int i){
        start = 0;
        classid = i;
        getData();
        myAdapter.notifyDataSetChanged();
    }

    private void selectFood(String selectfood){
        mData1.clear();
        bit.clear();
        start = 0;
        myAdapter.notifyDataSetChanged();
        getSelectData(selectfood);
    }
    private OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    private Gson gson = new Gson();
    private String result = "";
    private Map<String,Bitmap> bit = new HashMap<String, Bitmap>();
    int start = 0;
    private int classid = 2;
    private Handler myhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    Toast.makeText(context,"搜索失败",Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //将数据加载到listv
                    inImg();
                    break;
                case 2:
                    inData();
                    break;

            }
        }
    };
    private void getSelectData(String name){
        int num = 10;
        String values = "keyword="+name+"&num="+num+"&start="+start;
        Request request = new Request.Builder()
                .header("Authorization","APPCODE ad5df328957c4ccea6e5087649649be1")
                .url("http://jisusrecipe.market.alicloudapi.com/recipe/search?"+values)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = new Message();
                msg.what = 0;
                myhandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                result = response.body().string();
                Message msg = new Message();
                msg.what = 1;
                start+=10;
                myhandler.sendMessage(msg);
            }
        });
    }
    private void getData(){
        int num = 10;
        String values = "classid="+classid+"&num="+num+"&start="+start;
        Request request = new Request.Builder()
                .header("Authorization","APPCODE ad5df328957c4ccea6e5087649649be1")
                .url("http://jisusrecipe.market.alicloudapi.com/recipe/byclass?"+values)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = new Message();
                msg.what = 0;
                myhandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                result = response.body().string();
                Message msg = new Message();
                msg.what = 1;
                start+=10;
                myhandler.sendMessage(msg);
            }
        });
    }

    private void getImg(String url,final String name){
        Request request = new Request.Builder()
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                bit.put(null,null);
                if (bit.size() == 10){
                    Message msg = new Message();
                    msg.what = 2;
                    myhandler.sendMessage(msg);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] img = response.body().bytes();
                bit.put(name,BitmapFactory.decodeByteArray(img,0,img.length));
                if (bit.size() == 10){
                    Message msg = new Message();
                    msg.what = 2;
                    myhandler.sendMessage(msg);
                }
            }
        });
    }

    private void inImg(){
        AllResult allResult = gson.fromJson(result,AllResult.class);
        AllResult.theResult at = allResult.getResult();
        ArrayList<AllResult.ResultList> ar = at.getList();
        for (int i = 0; i < ar.size();i++) {
            getImg(ar.get(i).getPic(),ar.get(i).getName());
        }
    }

    private void inData(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
        String name = "";
        AllResult allResult = gson.fromJson(result,AllResult.class);
        AllResult.theResult at = allResult.getResult();
        ArrayList<AllResult.ResultList> ar = at.getList();
        for (int i = 0; i < ar.size();i++) {
            name = ar.get(i).getName();
            mData1.add(new FoodListView(bit.get(name),ar.get(i).getName(), ar.get(i).getTag(), ar.get(i).getContent()));
        }
        myAdapter.notifyDataSetChanged();
        bit.clear();
    }

    private void init(){
        mData1 = new ArrayList<FoodListView>();
        myAdapter = new MyListViewAdapter<FoodListView>((ArrayList)mData1,R.layout.adapter_listview_food) {
            @Override
            public void bindView(ViewHolder holder, FoodListView obj) {
                holder.setImageResource(R.id.img_list_food,obj.getImg());
                holder.setText(R.id.txt_list_title,obj.getTitle());
                holder.setText(R.id.txt_list_fenshu,obj.getFenshu());
                holder.setText(R.id.txt_list_content,obj.getContent());
            }
        };
        list.setAdapter(myAdapter);
    }
}
